package ltd.followkba.page;

import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Context;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.NonNull;
import androidx.viewpager.widget.PagerAdapter;
import androidx.viewpager.widget.ViewPager;

import com.google.android.material.tabs.TabLayout;
import com.kcbsdk.EventHandler;
import com.kcbsdk.MyManage.AUserFileType;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

import ltd.advskin.MRAM;
import ltd.advskin.MSKIN;
import ltd.advskin.base.BaseList;
import ltd.advskin.base.BasePage;

import ltd.advskin.base.KcListHolder;
import ltd.advskin.base.KcListListener;
import ltd.advskin.base.KcNoneListener;
import ltd.advskin.base.KcTypeListener;
import ltd.advskin.task.TaskFree;
import ltd.advskin.view.KcHeaderView;
import ltd.advskin.view.KcListView;
import ltd.followkba.MAPP;
import ltd.followkba.MDBS;
import ltd.followkba.R;
import ltd.followkba.task.BAppUser;
import ltd.followkba.task.BFileBase;
import ltd.followkba.task.LogTyp;
import main.MAPI;
import static ltd.advskin.MSKIN.MSTRING;
import static ltd.advskin.MSKIN.MTOAST;
import static ltd.advskin.MSKIN.showABeanErrorStr;
import static main.MAPI.MSLEEP;
import static main.MAPI.mMyUtils;
import static main.MAPI.mMyWorks;

public class DoneLogPage extends BaseList {
    private List<BFileBase>[] mBFileBase;
    private SimpleDateFormat mSimpleDateFormat;
    private String[] done_list_name;
    private LogTyp[] mLogTyps;
//    private long gTick;
//    private boolean isBusy;
//    private boolean isNormal;
//    private long gCheckTick;
    private int gWorksType;
    private boolean isClose;

    // 所有的页面都接受同样的方式打开LOG
    public static boolean logEnable;

    public void MLOG(String text) {
        if (logEnable) {
            MSTRING(MAPI.GET_LOG_NAME(this) + text);
        }
    }

    @Override
    public void onInitView() {                       // 使用者需要继承，初始化页面控件等显示
        setLayout(R.layout.page_done_list);
        mKcHeaderView = (KcHeaderView) findViewById(R.id.khvDone);
        mKcHeaderView.setTitle("已发出的评论", new KcTypeListener() {
            @Override
            public void onMessage(int type) {
                switch (type) {
                    case KcHeaderView.TYPE_CLICK_LEFT:
                        onFinish();
                        break;
                }
            }
        });
        done_list_name = MSKIN.getStringArray(R.array.done_list_name);
        mBFileBase = new List[done_list_name.length];
        for (int index = 0; index < done_list_name.length; index++){
            mBFileBase[index] = new ArrayList<>();
        }
        mLogTyps = new LogTyp[]{LogTyp.NORMAL_COMMENT, LogTyp.NEW_COMMENT, LogTyp.OLD_COMMENT, LogTyp.CARE_TEXT, LogTyp.GIFT_TEXT, LogTyp.ADVERT_TEXT, LogTyp.LOG_LIKE, LogTyp.LOG_FILE};
        mSimpleDateFormat = new SimpleDateFormat("MM-dd HH:mm:ss");
        initPageListView(1);
        new Thread(new Runnable() {
            public void run() {
                while (!isClose) {
                    for (int index = 0; index < done_list_name.length; index++) {
                        mBFileBase[index] = MDBS.getDoneLog(MAPP.mBDbsAccount, mLogTyps[index]);
                        if (mBFileBase[index] != null) {
                            Collections.sort(mBFileBase[index], new Comparator<BFileBase>() {
                                public int compare(BFileBase info1, BFileBase info2) {
                                    return info2.DateTime - info1.DateTime;                  // 降序
                                }
                            });
                        }
                        makeBFileBase(mBFileBase[index]);
                    }
                    MSLEEP(5000);
                    if (MRAM.mActivity != null) {
                        MRAM.mActivity.runOnUiThread(new Runnable() {
                            public void run() {
                                setListView(gTabSelect, (List) mBFileBase[gTabSelect]);
//                                mPagerAdapter.notifyDataSetChanged();

                            }
                        });
                    }
                }
            }
        }).start();
        gWorksType = MAPP.mBDbsAccount.WorksType;
    }

    @Override
    public void onInitData(){                                                                       // onInitView结束，开始加载数据
        mMyWorks.setUiEventCallBack(new EventHandler() {
            @Override
            public void onComplete(int methodType, boolean isFail, String message) {
                if (mMyWorks.isEventDataRefresh()){
                    showInfo();
                }
            }
        });
        showInfo();
    }
    @Override
    public void onPageUpdate(BasePage basePage) {    // 更新显示页面数据，用于刷新显示 basePage返回上面的页面，可以使用getPageResult()获得返回的内容
        onInitData();
    }
    @Override
    public void onFinish() {       // 使用者选择性继承，用户按了后退键，不继承就直接关闭了
        isClose = true;
        setClose();

    }

    private void showInfo() {
        int tabSel = getTabList();
        if (tabSel > 0) {
            tabSel -= 1;
            setListView(tabSel, (List) mBFileBase[tabSel]);
//            MLOG( String.format("System.currentTimeMillis C %s %s %s", tabSel, gTabSelect, System.currentTimeMillis()-gCheckTick));
        }
    }
    private void makeBFileBase(List<BFileBase> lists){
        if (gWorksType <= 32) {
            int length = (lists != null) ? lists.size() : 0;
            for (int index = 0; index < length; index++){
                BFileBase bFileBase = lists.get(index);
                bFileBase.UserID = MAPI.STRING_DEC32(bFileBase.UserIdS);
                bFileBase.FileID = MAPI.STRING_DEC32(bFileBase.WorksIdS);
            }
        }
    }
    private static final int[] item_done_list = new int[]{
            R.layout.item_done_list, 7,
            R.id.kbiDone, R.id.kbtWorksDone, R.id.tvUserDone, R.id.kbtTickDone,
            R.id.kbtTimeDone, R.id.kbtIdsDone,
            R.id.kbtTextDone,

    };
    ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
    // KcListView的全部处理，放在页面的最后位置统一处理 ///////////////////////////////////////////////////////////////////
    ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
    private void initListView(int tab, KcListView kcListView) {
        mKcListView[tab] = kcListView;
        mKcListView[tab].initView(null, item_done_list, null, new KcListListener() {
            @Override
            public int onMessage(int type, int tab, Object object) {
                return 0;
            }
            @Override
            public int onBindItemHolder(boolean skipImage, int tab, int position, final KcListHolder holder) {
//                MLOG(String.format("currentTimeMillis AB %s", position));
                BFileBase bFileBase = (BFileBase) getListView(tab, position);
                MSKIN.setText(bFileBase.WorksName, holder.mView[1]);
                if (gWorksType < 32 && bFileBase.UserID > 0) {
                    MSKIN.showUserHead(AUserFileType.IMG_SMALL, bFileBase, holder.mView[0]);
                }else if (bFileBase.HeadFile != null) {
                    holder.mView[0].setVisibility(View.VISIBLE);
                    MAPP.showUserHead(bFileBase.HeadFile, bFileBase, holder.mView[0]);

                }else {
                    holder.mView[0].setVisibility(View.GONE);
                    holder.mView[2].setVisibility(View.GONE);
                }
                if (bFileBase != null) {
                    MSKIN.setText(bFileBase.UserName, holder.mView[2]);
                    holder.mView[2].setTag(bFileBase.UserName);
                }
                holder.mView[2].setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        String text = (String)v.getTag();
                        ClipboardManager clipboardManager = (ClipboardManager) MRAM.mContext.getSystemService(Context.CLIPBOARD_SERVICE);
                        ClipData clipData = ClipData.newPlainText("Label", text);
                        clipboardManager.setPrimaryClip(clipData);   // 将ClipData内容放到系统剪贴板里。
                        MTOAST("复制 "+text);
                    }
                });

                MSKIN.setText(mMyUtils.getSmartDate(bFileBase.DateTime), holder.mView[3]);
                MSKIN.setText(bFileBase.WriteTime, holder.mView[4]);
                if (gWorksType < 32) {
                    MSKIN.setText(String.format("%s_%04x", bFileBase.UserID, bFileBase.FileID), holder.mView[5]);
                }
                MSKIN.setText(bFileBase.Text, holder.mView[6]);

                holder.mItemView.setTag(bFileBase);
                holder.mItemView.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        BFileBase bFileBase = (BFileBase)v.getTag();
                        BAppUser bAppUser = new BAppUser();
                        bAppUser.UserIdS = bFileBase.UserIdS;
                        MAPP.startUserHomePage(bAppUser, false);
                    }
                });

                return 0;
            }
        });
        // (d)列表最后更新日期时间 (n)下次更新日期时间 (c)当前数量 (q)列表最大的数量
        String headTips = String.format("共(c)条");
        mKcListView[tab].setStatus(true, false, headTips, "", "");
        mKcListView[tab].setTabNumber(tab);
    }

    private void initPageListView(int tabQty) {
        ViewPager viewPager = findViewById(R.id.vpDone);
        TabLayout tabLayout = findViewById(R.id.tlDone);;
        mKcListView = new KcListView[done_list_name.length];
        mPagerAdapter = new PagerAdapter() {
            @Override
            public int getCount() {
                return done_list_name.length;
            }
            @Override
            public CharSequence getPageTitle(int position) {
                return done_list_name[position];
            }
            @Override
            public boolean isViewFromObject(@NonNull View view, @NonNull Object object) {
                return view == object;
            }
            @Override
            public Object instantiateItem(ViewGroup container, int position) {
                KcListView kcListView = new KcListView(getActivity(), null);
                initListView(position, kcListView);
                container.addView(kcListView);
                setTabList(position);                               // 设置Tab的位置
                return kcListView;
            }
            @Override
            public void destroyItem(ViewGroup container, int position, Object object) {
                container.removeView(mKcListView[position]);
                mKcListView[position] = null;
            }
        };
        viewPager.setAdapter(mPagerAdapter);
        viewPager.setCurrentItem(gTabSelect);
        tabLayout.setupWithViewPager(viewPager);
        tabLayout.setTabMode(TabLayout.MODE_SCROLLABLE);       // 设置TabLayout的模式   MODE_SCROLLABLE为滑动模式  MODE_FIXED为不滑动模式
        tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
            @Override
            public void onTabUnselected(TabLayout.Tab tab) {
            }
            @Override
            public void onTabSelected(TabLayout.Tab tab) {   // 顶部Tab选择
                byte tabSel = (byte) tab.getPosition();
                if (gTabSelect != tabSel) {                 // Tab的选择
                    gTabSelect = tabSel;
                    setTabList(tabSel);                     // 设置Tab的位置
                }
            }
            @Override
            public void onTabReselected(TabLayout.Tab tab) {
            }
        });
    }

}

